﻿package com.cn.lcc.util.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author lcc  
 * @date 2017年6月12日
 * @备注  http工具类 
 */
public class HttpUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	//发送json请求
	 public static StringBuilder sendJsonPost(String url, String param) {
		 if (url==null)
		 {
			 return new StringBuilder("NETWORKURLERROR");
		 }
	        PrintWriter out = null;
	        BufferedReader in = null;
	        StringBuilder result = new StringBuilder("");
	        	try {  
	        		logger.info(param);
	        		URL realUrl = new URL(url);// 创建连接  
	                HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();  
	                connection.setDoOutput(true);  
	                connection.setDoInput(true);  
	                connection.setUseCaches(false);  
	                connection.setInstanceFollowRedirects(true);  
	                connection.setRequestMethod("POST"); // 设置请求方式  
	                connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
	                connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
	                connection.connect();  
	                OutputStreamWriter out1 = new OutputStreamWriter(  
	                        connection.getOutputStream(), "UTF-8"); // utf-8编码  
	                out1.append(param);  
	                out1.flush();  
	                out1.close();  
	                // 读取响应  
	             // 定义BufferedReader输入流来读取URL的响应
		            in = new BufferedReader(
		                    new InputStreamReader(connection.getInputStream(),"UTF-8"));
		            String line;
		            while ((line = in.readLine()) != null) {
		            	result.append(line);
		            }
	            
	        } catch (Exception e) {
	        	logger.error("发送 POST 请求出现异常！"+e);
	            e.printStackTrace();
	            return new StringBuilder("NETWORKERROR");
	        }
	        //使用finally块来关闭输出流、输入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	            	logger.error("io流关闭错误！"+ex);
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }  
}
